package com.example.demo.job;

import com.aliyuncs.exceptions.ClientException;
import com.baidu.bas.db.dao.EruptDao;
import com.baidu.bas.db.dao.EruptJpaDao;
import com.deepzero.mmma.channel.AccountType;
import com.deepzero.mmma.channel.OperationResult;
import com.deepzero.mmma.channel.sms.account.AliSmsAccount;
import com.deepzero.mmma.channel.sms.manager.AliSmsManager;
import com.example.demo.enums.AuditStatus;
import com.example.demo.model.Account;
import com.example.demo.model.SmsTemplate;
import com.example.demo.service.TryService;
import com.google.common.util.concurrent.AtomicLongMap;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaQuery;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.function.Consumer;

/**
 * @author liuzhenchuan@foxmail.com
 * @date 2021/1/13
 */
@Component
@Slf4j
public class SmsTemplateJob {

    @Resource
    private EruptDao eruptDao;

    @Resource
    private EruptJpaDao eruptJpaDao;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private TryService tryService;

    private static final AtomicLongMap<Long> errorCounter = AtomicLongMap.create();

    @Scheduled(fixedRate = 60 * 1000,initialDelay = 30*1000)
    @Transactional(rollbackOn = Exception.class)
    public void updateStatus(){
        val data = eruptDao.createQuery("from SmsTemplate as t where t.account.type = '" +  AccountType.aliyunSMS + "' " +
                " and t.status in ('AUDINING', 'FINISHED_FAILED') ").getResultList();
        for(Object obj : data){
            SmsTemplate smsTemplate = (SmsTemplate) obj;
            if(errorCounter.get(smsTemplate.getId())>10){
                log.info("任务[{}]重试达到最大次数,忽略.", smsTemplate.getId());
                continue;
            }
            updateAliyunSmsTemplate(smsTemplate);
        }

    }

    public void updateAliyunSmsTemplate(SmsTemplate smsTemplate){
        Account account = tryService.getAccount(smsTemplate.getAccount().getId());
        AliSmsManager manager = new AliSmsManager((AliSmsAccount) account.getConfig());
        OperationResult<Integer> result;
        try {
            result = manager.queryTemplateStatus(smsTemplate.getOuterId());
        } catch (ClientException e) {
            log.warn("获取模板[{}]状态失败. 当前失败重试次数: {} ",smsTemplate.getOuterId(),errorCounter.get(smsTemplate.getId()),e);
            errorCounter.incrementAndGet(smsTemplate.getId());
            return;
        }
        if(result.isSuccess()){
            if(result.getData()==1){
                jdbcTemplate.update("update ma_sms_tempalte set update_time = ? , status = ? where id = ? ",
                        new Object[]{new Date(),AuditStatus.FINISHED_SUCCESS.name(),smsTemplate.getId()});
            }
            if(result.getData()==2){
                jdbcTemplate.update("update ma_sms_tempalte set update_time = ? , status = ? , info = ? where id = ? ",
                        new Object[]{new Date(),AuditStatus.FINISHED_FAILED.name(),result.getInfo(), smsTemplate.getId()});
            }
        }else{
            log.warn("获取状态失败.{}",result);
        }
    }

}
